/**
 * 用户管理接口模块
 */
const express = require('express')
const user = express.Router()

// 引入数据库
const db = require('../utils/db')
// 引入生成随机字符插件
const { v4: uuidv4 } = require('uuid')
// 引入oss存储图片
const { deldata, pushdata } = require('../utils/myoss')

/* 登录用户操作 */
user.post('/login', (req, res) => {
   const { username, pass } = req.body
   const sql = `SELECT * FROM users WHERE username='${username}' AND pass='${pass}'`
   db.query(sql, async (err, results) => {
      if (results.length > 0) {
         const info_obj = await getUserInfo(results[0].id)
         // 设置一条用户 cookie
         res.cookie('username', username, { maxAge: 24 * 60 * 60 * 1000 })
         res.json({ code: 1, msg: 'ok', data: { ...results[0], ...info_obj } })
      } else {
         res.json({ code: 0, msg: 'failed', data: {} })
      }
   })
})
/* 使用浏览器cookie中存储的用户名实现登陆 */
user.post('/cookieLogin', (req, res) => {
   const { username } = req.body
   const sql = `SELECT * FROM users WHERE username='${username}'`
   db.query(sql, async (err, results) => {
      if (results.length > 0) {
         const info_obj = await getUserInfo(results[0].id)
         res.statusCode = 200
         res.json({ code: 1, msg: 'ok', data: { ...results[0], ...info_obj } })
      } else {
         res.json({ code: 0, msg: 'failed', data: {} })
      }
   })
})
// 获取用户头像
function getUserInfo(u_id) {
   return new Promise((resolve, rejecte) => {
      db.query(`SELECT realname,pic,phone,email,u_id,nickname FROM user_info WHERE u_id=${u_id}`, (err, results) => {
         if (err) return rejecte({})
         if (results.length >= 1) {
            resolve(results[0])
         } else {
            resolve({})
         }
      })
   })
}

/* 更新用户数据 */
user.post('/updateuserinfo', async (req, res) => {
   const { u_id, nickname, picdata, pictype, phone, email, oldFileName } = req.body
   let sql = '', base64 = '', newFileName = ''
   if (picdata) {
      newFileName = `${uuidv4().replace(/-/g, '')}.${pictype}`
      base64 = picdata.replace(/^data:image\/\w+;base64,/, '')
      sql = `
         UPDATE user_info SET pic='${newFileName}', phone='${phone}',email='${email}',nickname='${nickname}' WHERE u_id=${u_id};
         UPDATE comments SET userpic='${newFileName}' WHERE user_id=${u_id};
         UPDATE comments SET comments_user='${nickname}' WHERE user_id=${u_id};
      `
   } else {
      sql = `
         UPDATE user_info SET phone='${phone}',email='${email}',nickname='${nickname}' WHERE u_id=${u_id};
         UPDATE comments SET comments_user='${nickname}' WHERE user_id=${u_id};
      `
   }
   db.query(sql, async (err, results) => {
      if (results.length >= 1) {
         if (picdata) {
            // 删除oss对应的文件
            await deldata('avatar/' + oldFileName)
            // 上传图片到oss中的avatar目录下
            await pushdata('avatar/' + newFileName, new Buffer(base64, "base64"))
         }
         res.json({ code: 1, msg: 'ok' })
      } else {
         res.json({ code: 0, msg: 'failed' })
      }
   })
})

/* 注册用户操作 */
user.post('/register', (req, res) => {
   const { username, pass } = req.body
   const sql = `INSERT INTO users(username,pass) VALUES('${username}','${pass}')`
   db.query(sql, (err, results) => {
      if (results.affectedRows >= 1) {
         // 设置用户 cookie
         res.cookie('username', username, { maxAge: 24 * 60 * 60 * 1000 })
         res.json({ msg: 'ok', username, code: 1, u_id: results.insertId })
      }
      else res.json({ username: '', msg: 'failed', code: 0 })
   })
})
/* 存储注册成功后用户的基础信息 */
user.post('/inituserinfo', (req, res) => {
   const { pic, u_id } = req.body
   const sql = `INSERT INTO user_info(u_id,pic) VALUES(${Number(u_id)},'${pic}')`
   db.query(sql, (err, results) => {
      if (results.affectedRows >= 1) {
         res.json({ code: 1, msg: 'ok' })
      } else res.json({ code: 0, msg: 'failed' })
   })
})

/* 退出登陆操作 */
user.post('/logout', (req, res) => {
   res.clearCookie('username')
   res.json({ msg: 'ok', code: 1 })
})

// 暴露接口
module.exports = user